package com.youens.navigationdrawertest.ui.photograph

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider


import androidx.fragment.app.Fragment

import androidx.lifecycle.ViewModelProviders
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import com.xiasuhuei321.loadingdialog.view.LoadingDialog
import com.youens.navigationdrawertest.MainActivity

import com.youens.navigationdrawertest.R
import com.youens.navigationdrawertest.album.GetPhotoFromAlbum
import com.youens.navigationdrawertest.database.DataBaseUtils
import com.youens.navigationdrawertest.identification.Base64Util
import com.youens.navigationdrawertest.identification.FileUtil
import com.youens.navigationdrawertest.identification.HttpUtil
import kotlinx.android.synthetic.main.fragment_photograph.*
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.util.*
import kotlin.collections.ArrayList


class PhotographFragment : Fragment() {

    //设置权限请求和活动请求的请求码requestCode
    companion object {
        private const val PERMISSIONS_REQUEST_ALBUM = 1
        private const val PERMISSIONS_REQUEST_CAMERA = 2

        private const val ACTIVITY_REQUEST_ALBUM = 3
        private const val ACTIVITY_REQUEST_CAMERA = 4
    }

    private lateinit var photographViewModel: PhotographViewModel

    lateinit var cameraSavePath: File
    lateinit var cameraSaveDir: File
    lateinit var uri: Uri
    lateinit var imageView: ImageView
    lateinit var resultTextView:TextView
    lateinit var translationTextView:TextView
    lateinit var photoPath:String
    lateinit var databaseUtil: DataBaseUtils
    lateinit var loadingDialog: LoadingDialog

    //拍照需要的两个权限
    private val permissionList = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
    //存储用户拒绝授权的权限
    var permissionTemp: ArrayList<String> = ArrayList()

    // 绑定组件
    override fun onStart() {
        super.onStart()
        imageView = view!!.findViewById(R.id.iv_image_view)
        resultTextView = view!!.findViewById<TextView>(R.id.result)
        translationTextView = view!!.findViewById<TextView>(R.id.translation)

        initListener()
    }

    // 只执行一次
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        photoPath = ""
        databaseUtil = (activity as MainActivity).getDataBaseUtils()
        //拍照的文件存储位置
        cameraSaveDir = File(Environment.getExternalStorageDirectory().path + "/cameraTest/")
        if (!cameraSaveDir.exists()) {
            cameraSaveDir.mkdir()
        }


    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        photographViewModel =
            ViewModelProviders.of(this).get(PhotographViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_photograph, container, false)
        //val textView: TextView = root.findViewById(R.id.text_home)
        //homeViewModel.text.observe(this, Observer {
        //    textView.text = it
        //})


        return root
    }


    fun showLoading(){
        loadingDialog = LoadingDialog(activity)
        loadingDialog.setLoadingText("加载中...")
        loadingDialog.setSuccessText("加载成功")
        loadingDialog.setFailedText("加载失败")
        loadingDialog.closeSuccessAnim()
        loadingDialog.closeFailedAnim()
        loadingDialog.show()
    }
    //设置button的监听
    private fun initListener() {

        //相册监听，检查一个权限
        btn_album.setOnClickListener {
            //检查版本是否大于M
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        activity!!.applicationContext,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSIONS_REQUEST_ALBUM
                    )
                } else {
                    //权限已经被授权，开启相册
                    goAlbum()
                }
            }
        }

        //拍照监听，检查两个权限
        btn_camera.setOnClickListener {
            permissionTemp.clear()
            for (i in permissionList.indices) {
                if (ContextCompat.checkSelfPermission(
                        activity!!.applicationContext,
                        permissionList[i]
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    permissionTemp.add(permissionList[i])
                }
            }
            if (permissionTemp.isEmpty()) {
                //未授予的权限为空，表示都授予了，开启照相功能
                goCamera()
            } else {//请求权限方法
                val permissions = permissionTemp.toTypedArray()//将List转为数组
                ActivityCompat.requestPermissions(
                    activity!!,
                    permissions,
                    PERMISSIONS_REQUEST_CAMERA
                )
            }
        }

        btn_identify_and_translate.setOnClickListener {
            //检查版本是否大于M
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(
                        activity!!,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    ActivityCompat.requestPermissions(
                        activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSIONS_REQUEST_ALBUM
                    )
                } else {
                    if(photoPath!=""){

                        identifyAndTranslate(photoPath)
                        showLoading()
                        databaseUtil.updatePunchChockProgress(Date().time)

                    }else{
                        Toast.makeText(activity,"请选择照片",Toast.LENGTH_LONG).show()
                    }
                }
            }
        }

        btn_add_favourite.setOnClickListener {
            if (resultTextView.text.equals("识别：") || translationTextView.text.equals("翻译：")){
                Toast.makeText(activity,"请先识别并翻译！",Toast.LENGTH_LONG).show()
                Log.d("TAG","请先识别并翻译")
            }else{
                var result = resultTextView.text.substring(resultTextView.text.indexOf("：")+1)
                var translateResult = translationTextView.text.substring(translationTextView.text.indexOf("：")+1)
                var id = databaseUtil.getWordsId(translateResult)
                databaseUtil.addFavourite(id, Date().time)
                Toast.makeText(activity,"收藏成功！",Toast.LENGTH_LONG).show()
            }
        }
    }

    //权限结果回调
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {

        when (requestCode) {

            //相册权限请求结果
            PERMISSIONS_REQUEST_ALBUM -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    goAlbum()
                } else {
                    Toast.makeText(activity, "你拒绝了读取相册权限", Toast.LENGTH_SHORT).show()
                }
            }

            //拍照权限请求结果
            PERMISSIONS_REQUEST_CAMERA -> {
                //用于判断是否有未授权权限，没有则开启照相
                var isAgree = true
                for (i in grantResults.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //检查到有未授予的权限
                        isAgree = false
                        //判断是否勾选禁止后不再询问
                        val showRequestPermission =
                            ActivityCompat.shouldShowRequestPermissionRationale(activity as Activity, permissions[i])
                        if (showRequestPermission) {
                            Toast.makeText(activity, "你拒绝了拍照相关权限", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                //isAgree没有被置为false则表示权限都已授予，开启拍照
                if (isAgree) {
                    goCamera()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    //相册功能
    private fun goAlbum() {
        val intent = Intent()
        intent.action = Intent.ACTION_PICK
        intent.type = "image/*"
        startActivityForResult(intent, ACTIVITY_REQUEST_ALBUM)
    }

    //拍照功能
    private fun goCamera() {
        cameraSavePath = File(Environment.getExternalStorageDirectory().path + "/cameraTest/" + System.currentTimeMillis() + ".jpg")
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity!!.applicationContext, "com.youens.navigationdrawertest.fileprovider", cameraSavePath)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            uri = Uri.fromFile(cameraSavePath)
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)

        this.startActivityForResult(intent, ACTIVITY_REQUEST_CAMERA)
    }

    //活动请求的回调，用requestCode来匹配
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {


        //相册
        if (requestCode == ACTIVITY_REQUEST_ALBUM && resultCode == Activity.RESULT_OK) {

            photoPath = GetPhotoFromAlbum.getRealPathFromUri(activity!!.applicationContext, data!!.data)!!
            imageView.setImageURI(Uri.parse(photoPath))

            //拍照
        } else if (requestCode == ACTIVITY_REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {

            photoPath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                cameraSavePath.toString()
            } else {
                uri.encodedPath
            }
            imageView.setImageURI(Uri.parse(photoPath))

        }
        super.onActivityResult(requestCode, resultCode, data)
    }



    private fun identifyAndTranslate(filePath:String) {
        // 请求url
        Thread()
        {
            val url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
            var result:String?=null
            var translateResult:String?=null
            try {
                val imgData: ByteArray = FileUtil.readFileByBytes(filePath)
                val imgStr: String = Base64Util.encode(imgData) //
                val imgParam: String = URLEncoder.encode(imgStr, "UTF-8")
                val param = "image=$imgParam"

                // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
                val accessToken = "24.a4e40dff1e38f92e7c756ee5e9d54184.2592000.1612446626.282335-23486253"
                result = HttpUtil.post(url, accessToken, param)


                //解析识别得到的json数据，得到实体对象链表类
                val gson = Gson() //创建Gson对象
                val jsonParser = JsonParser()
                val jsonElements: JsonArray = jsonParser.parse(result).getAsJsonObject().get("result") as JsonArray//获取JsonArray对象
                val beans: java.util.ArrayList<info> = java.util.ArrayList()
                for (bean in jsonElements) {
                    val bean1: info = gson.fromJson<info>(bean, info::class.java) //解析
                    beans.add(bean1)
                }
                //遍历实体对象链表类，调用API得到翻译结果
                val beans1: java.util.ArrayList<translate> = java.util.ArrayList() //存储翻译结果

                var s:String? = beans.get(0).keyword
                result=s
                var url = URL("http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i="+s)
                var connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connectTimeout = 10000
                var jsonString = connection.getInputStream()
                val str = BufferedReader(InputStreamReader(jsonString)).useLines { lines ->
                    val results = StringBuilder()
                    lines.forEach { results.append(it) }
                    results.toString()
                }
                val jsonParser1 = JsonParser()
                val jsonElements1: JsonArray = jsonParser1.parse(str).getAsJsonObject().get("translateResult") as JsonArray//获取JsonArray对象
                val a:String = jsonElements1[0].toString()
                val b: JsonArray = jsonParser.parse(a).getAsJsonArray() //获取JsonArray对象
                for (bean2 in b) {
                    val bean3: translate= gson.fromJson<translate>(bean2, translate::class.java) //解析
                    beans1.add(bean3)
                }
                connection.disconnect()

                //下列代码为获取翻译结果的方法：

                var s1:String? = beans1.get(0).tgt
                translateResult = s1

                val id = databaseUtil.getWordsId(translateResult!!)
                if(id<0){
                    databaseUtil.addWords(translateResult!!,result!!,java.util.Date().time,filePath)
                }


                activity!!.runOnUiThread {
                    resultTextView.text = "识别："+result
                    translationTextView.text = "翻译："+translateResult
                    loadingDialog.loadSuccess()
                    Toast.makeText(activity,"识别成功！",Toast.LENGTH_SHORT).show()
                }

            } catch (e: Exception) {
                activity!!.runOnUiThread {
                    loadingDialog.loadFailed()
                    Toast.makeText(activity,"识别失败！",Toast.LENGTH_SHORT).show()
                }

                e.printStackTrace()
            }

        }.start()
    }

    private data class info(
        val score:Double?,
        val root: String?,
        val keyword: String?
    )

    private data class translate(
        val src:String?,
        val tgt:String?
    )


}